import java.io.IOException;
import java.net.DatagramPacket;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;

class RequestRemainingChunks extends Thread
{
	private static final int maxChunksPerGet = 30;
	
	Peer parent = null;
	
	public RequestRemainingChunks(Peer parent)
	{
		this.parent = parent;
	}

	public void run()
	{
		while(true)
		{
			if(!parent.downloadingfiles.files.isEmpty())
			{
				Set<Entry<String, DownloadingFiles.DFile>> set = parent.downloadingfiles.files.entrySet();
				Iterator<Entry<String, DownloadingFiles.DFile>> itr = set.iterator();
				
				while(itr.hasNext()) 
				{
					Entry<String,DownloadingFiles.DFile> e = itr.next();
					if(!e.getValue().remainingchunks.isEmpty())
					{
						int index = 0;
						for(index = 0 ; index+maxChunksPerGet < e.getValue().remainingchunks.size(); index +=maxChunksPerGet)
						{
							String chunks = new String();
							for(int i=index; i < index+maxChunksPerGet;++i)
							{
								chunks+= e.getValue().remainingchunks.get(i);
								chunks +=",";
							}
							
							String toSend =  QueryFactory.get(e.getKey(), chunks.substring(0, chunks.length()-1));
							DatagramPacket d = new DatagramPacket(toSend.getBytes(),toSend.length(),parent.address,parent.controlport);
							try {
								parent.controlSocket.send(d);
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
						
						String chunks = new String();
						for(int i=index; i < e.getValue().remainingchunks.size();++i)
						{
							chunks+= e.getValue().remainingchunks.get(i);
							if(i+1 != e.getValue().remainingchunks.size())
								chunks +=",";
						}
						String toSend =  QueryFactory.get(e.getKey(), chunks);
						DatagramPacket d = new DatagramPacket(toSend.getBytes(),toSend.length(),parent.address,parent.controlport);
						try {
							parent.controlSocket.send(d);
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						
					}
					else
						parent.downloadingfiles.files.remove(e.getKey());
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}					